

//中缀表达式放入数组
function toInfixExpression(str){
  let reg = new RegExp(/\d/)
  let infixArr = [];
  let index = 0;
  let len = str.length;
  //遍历字符串，提取出数字和字符串
  for(let i = 0; i< len; i++){
    //数字情况
    if(reg.test(str[i])){
      if(str[i + 1] && !reg.test(str[i + 1])){
        infixArr.push(str.slice(index, i + 1)) ;
      } else if(!str[i + 1]){
        infixArr.push(str[i]);
      }
    } else {  //运算符直接入数组
      infixArr.push(str[i]);
      index = i + 1;
    }
  }

  return infixArr;
}
//中缀转后缀
function parsesuffixExpression(arr){
  let reg = new RegExp(/\d/)
  let temp = [];
  let stack = [];
  let len = arr.length
  for(let i = 0; i<len; i++){
    if(reg.test(arr[i])){ //数字直接放入返回数组
      temp.push(arr[i]);
    } else {
      if(!stack.length || arr[i] === '('){  //如果栈数组没有运算符或者为（，就直接放入返回数组
        stack.push(arr[i]);
      } else if(arr[i] === ')'){  //遇到）
        while(stack[stack.length - 1] !== '('){
          temp.push(stack.pop());
        }
        stack.pop();  //将（出栈
      } else {
        //如果栈有运算符，且栈顶不是（，就不断地比较，大于栈顶就直接入栈，反之将栈顶出栈
        while(stack[stack.length - 1] !== '(' && priority(stack[stack.length - 1]) >= priority(arr[i])){
          if(!stack.length){
            break;
          }
          temp.push(stack.pop());
        }
        stack.push(arr[i])
      }
    }
  }
  while(stack.length){
    temp.push(stack.pop()); //出栈剩下的
  }
  return temp;
}
function countNum(n1, n2, com){
  switch(com) {
    case '+':
      return n1 + n2;
    case '-':
      return n1 - n2;
    case '*':
      return n1 * n2;
    case '/':
      return n1 / n2;
    default: return;
  }
}
function priority(com){
  if(com === '*' || com === '/'){
    return 1;
  } else if(com === '-' || com === '+'){
    return 0;
  }
}
//运算后缀表达式
function computedsuffix(suffix){
  let stack = [];
  let len = suffix.length;
  let reg = new RegExp(/\d/);
  for(let i = 0; i<len; i++){
    if(reg.test(suffix[i])){
      stack.push(suffix[i]);
    } else {
      let num1 = Number(stack.pop());
      let num2 = Number(stack.pop());
      stack.push(countNum(num2, num1, suffix[i]));
    }
  }
  return stack.pop();
}

let arr = toInfixExpression("3-4*(7+6)");
let suffix = parsesuffixExpression(arr);
console.log(computedsuffix(suffix));